<template>
  <view class="abnormal-order-container">
    <status-bar bgColor="#0088ff"></status-bar>
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="back-btn" @click="goBack">
        <image src="/static/images/icon/backward_flat.png" class="back-icon-img"></image>
      </view>
      <view class="nav-title">异常订单</view>
    </view>
    
    <!-- 订单列表 -->
    <scroll-view scroll-y class="order-list">
      <block v-for="(order, index) in orderList" :key="index">
        <!-- 订单项 -->
        <view class="order-item">
          <!-- 预约时间 -->
          <view class="appointment-time">
            <text>预约时间：</text>
            <text class="time-value">{{order.appointmentTime}}</text>
          </view>
          
          <!-- 订单编号和标签 -->
          <view class="order-header">
            <view class="order-no-container">
              <text class="order-no">订单编号：{{order.orderNo}}</text>
              <view v-if="order.tag" class="order-tag" :class="getTagClass(order.tag)">
                <text class="tag-icon">!</text>
                {{order.tag}}
              </view>
            </view>
          </view>
          
          <!-- 客户信息和服务类型 -->
          <view class="customer-info">
            <view class="customer-left">
              <view class="location-icon">
                <image src="/static/images/icon/location.png" class="icon-img"></image>
              </view>
              <view class="customer-details">
                <view class="customer-name">{{order.customerName}}</view>
                <view class="service-type-tag" :class="getServiceTypeClass(order.orderType)">{{order.orderType == '1'? '窗帘测量': '窗帘安装'}}</view>
              </view>
            </view>
            <view class="service-status">
              <text>{{getOrderStatusText(order.orderStatus)}}</text>
              <text class="price">￥{{order.masterOrderFee}}</text>
            </view>
          </view>
          
          <!-- 地址 -->
          <view class="order-address">
            <text class="address-text">{{order.address}}</text>
          </view>
          
          <!-- 异常信息 -->
          <view class="abnormal-reason" v-if="order.operateDescription">
            <text class="reason-label">备注：</text>
            <text class="reason-text">{{order.operateDescription || ''}}</text>
          </view>

          <!-- 查看详情按钮 -->
          <view class="order-footer">
            <button class="detail-btn" @click="viewOrderDetail(order)">查看详情</button>
          </view>
        </view>
      </block>
      
      <!-- 加载中提示 -->
      <view class="loading-tip" v-if="loading">
        <uni-load-more status="loading" :contentText="{ contentdown: '加载中...', contentrefresh: '加载中...', contentnomore: '没有更多数据了' }"></uni-load-more>
      </view>
      
      <!-- 无数据提示 -->
      <view class="empty-tip" v-if="!loading && noData">
        <image src="/static/images/empty.png" mode="aspectFit" class="empty-image"></image>
        <text>暂无异常订单</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { ordeList } from '@/api/app/master/order.js'
import uniLoadMore from '@/uni_modules/uni-load-more/components/uni-load-more/uni-load-more.vue'

export default {
  components: {
    uniLoadMore
  },
  data() {
    return {
      orderList: [],
      loading: false,
      noData: false,
      pageNum: 1,
      pageSize: 10,
      total: 0
    }
  },
  onLoad() {
    // 加载异常订单数据
    this.loadAbnormalOrders()
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.pageNum = 1
    this.loadAbnormalOrders().then(() => {
      uni.stopPullDownRefresh()
    })
  },
  // 上拉加载更多
  onReachBottom() {
    if (this.orderList.length < this.total) {
      this.pageNum++
      this.loadAbnormalOrders()
    }
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },
    
    // 获取标签样式类
    getTagClass(tag) {
      if (tag === '加急') {
        return 'urgent-tag'
      }
      return ''
    },
    
    // 获取服务类型样式类
    getServiceTypeClass(type) {
      if (type == '1') {
        return 'measure-tag'
      } else if (type == '2') {
        return 'install-tag'
      }
      return ''
    },
    
    // 获取订单状态文本
    getOrderStatusText(status) {
      /** 订单状态
      * 1：待派单；
      * 2：待预约；
      * 3：待服务；
      * 4：待验收；
      * 5：已完成；
      * 9：已售后；
      * 99：异常订单；
      */
      const statusMap = {
        '1': '待派单',
        '2': '待预约',
        '3': '待服务',
        '4': '待验收',
        '5': '已完成',
        '9': '已售后',
        '99': '异常订单'
      };
      return statusMap[status] || '异常订单'; // 如果没有匹配的状态，默认显示"异常订单"
    },
    
    // 查看订单详情
    viewOrderDetail(item) {
        const status = this.getOrderStatusText(item.orderStatus);
       console.log(status)
      // 如果订单状态是"待预约"，跳转到预约操作页面
      if (status === '待预约' || status === '异常订单') {
        uni.navigateTo({
          url: '/pages/order/order-appointment?id=' + item.id
        });
      } 
      // 如果订单状态是"待服务"，跳转到订单详情页面
      else if (status === '待服务' || status === '待验收' || status === '已完成' || status === '已售后')   {
        uni.navigateTo({
          url: '/pages/order/order-detail?id=' + item.id
        });
      }
      else {
        // 其他状态的订单暂时只显示提示
        uni.showToast({
          title: '查看订单: ' + id,
          icon: 'none'
        });
      }


      // 实际项目中应该跳转到订单详情页
    },
    
    // 处理异常订单
    handleAbnormalOrder(order) {
      uni.showToast({
        title: '处理异常订单: ' + order.orderNo,
        icon: 'none'
      })
      // 实际项目中应该跳转到处理异常订单的页面或弹出处理异常订单的弹窗
    },
    
    // 姓名脱敏处理
    maskName(name) {
      if (!name) return '';
      if (name.length === 1) return name;
      if (name.length === 2) return name.substring(0, 1) + '*';
      return name.substring(0, 1) + '*'.repeat(name.length - 2) + name.substring(name.length - 1);
    },
    
    // 加载异常订单数据
    loadAbnormalOrders() {
      this.loading = true;
      this.noData = false;
      
      // 构建请求参数
      const params = {
        orderStatus: 99 // 异常订单状态码
      };
      
      // 调用接口获取异常订单数据
      return ordeList(params).then(res => {
        if (res.code === 200) {
          // 获取数据成功
          const orders = res.rows || [];
          this.total = res.total || 0;
          
          if (this.pageNum === 1) {
            this.orderList = [];
          }
          
          if (orders.length === 0 && this.pageNum === 1) {
            this.noData = true;
          }
          
          // 处理返回的数据
          const processedOrders = orders.map(item => {
            // 格式化预约时间为 yyyy-MM-dd HH:mm
            let formattedTime = '';
            if (item.reservationTime) {
              const dateTime = new Date(item.reservationTime);
              if (!isNaN(dateTime.getTime())) {
                const year = dateTime.getFullYear();
                const month = (dateTime.getMonth() + 1).toString().padStart(2, '0');
                const day = dateTime.getDate().toString().padStart(2, '0');
                const hours = dateTime.getHours().toString().padStart(2, '0');
                const minutes = dateTime.getMinutes().toString().padStart(2, '0');
                formattedTime = `${year}-${month}-${day} ${hours}:${minutes}`;
              } else {
                formattedTime = item.reservationTime;
              }
            }
            
            return {
              id: item.id,
              appointmentTime: formattedTime,
              orderNo: item.orderNo || '',
              tag: item.urgent == 1 ? '加急' : '',
              customerName: item.ownerName ? this.maskName(item.ownerName) : '',
              customerAvatar: item.customerAvatar || '/static/images/profile.jpg',
              serviceType: item.measureDescribe || '',
              orderType: item.orderType || '1', // 添加订单类型，默认为1（窗帘测量）
              address: item.ownerProvincial+item.ownerCity+item.ownerCounty+item.ownerAddress || '',
              price: item.orderFee || '0.00',
              masterOrderFee: item.masterOrderFee || '0.00',
              orderStatus: item.orderStatus || '99', // 添加订单状态，默认为99（异常订单）
              orderNotes: item.orderNotes || '', // 异常原因
              operateDescription: item.operateDescription || '',
            };
          });
          
          this.orderList = [...this.orderList, ...processedOrders];
        } else {
          // 获取数据失败
          uni.showToast({
            title: res.msg || '获取异常订单数据失败',
            icon: 'none'
          });
          if (this.pageNum === 1) {
            this.noData = true;
            this.orderList = [];
          }
        }
      }).catch(err => {
        console.error('获取异常订单数据失败:', err);
        uni.showToast({
          title: '获取异常订单数据失败，请稍后重试',
          icon: 'none'
        });
        if (this.pageNum === 1) {
          this.noData = true;
          this.orderList = [];
        }
      }).finally(() => {
        this.loading = false;
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.abnormal-order-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  height: 90rpx;
  background-color: #0088ff;
  color: #fff;
  padding: 0 30rpx;
  position: relative;
}

.back-btn {
  position: absolute;
  left: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon-img {
  width: 40rpx;
  height: 40rpx;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  font-weight: bold;
}

/* 订单列表 */
.order-list {
  height: calc(100vh - 90rpx);
  padding: 20rpx;
  background-color: #f5f5f5;
}

.order-item {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: 20rpx;
  position: relative;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

/* 预约时间 */
.appointment-time {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
}

.time-value {
  color: #ff8c00;
  font-size: 32rpx;
  font-weight: bold;
}

/* 订单编号和标签 */
.order-header {
  margin-bottom: 20rpx;
}

.order-no-container {
  display: flex;
  align-items: center;
}

.order-no {
  font-size: 28rpx;
  color: #333;
}

.order-tag {
  font-size: 24rpx;
  padding: 4rpx 12rpx;
  border-radius: 6rpx;
  margin-left: 10rpx;
  color: #fff;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.tag-icon {
  display: inline-block;
  width: 20rpx;
  height: 20rpx;
  line-height: 20rpx;
  text-align: center;
  border-radius: 50%;
  background-color: #fff;
  color: #ff3b30;
  font-weight: bold;
  margin-right: 4rpx;
  font-size: 20rpx;
}

.urgent-tag {
  background-color: #ff3b30;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.05);
    opacity: 0.8;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 客户信息和服务类型 */
.customer-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.customer-left {
  display: flex;
  align-items: center;
}

.location-icon {
  width: 50rpx;
  height: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10rpx;
}

.icon-img {
  width: 40rpx;
  height: 40rpx;
}

.customer-details {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.customer-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-right: 15rpx;
}

.service-type-tag {
  font-size: 24rpx;
  padding: 4rpx 16rpx;
  border-radius: 30rpx; /* 使用更大的圆角实现胶囊形状 */
  color: #fff;
  display: inline-block;
  line-height: 1.5;
}

.measure-tag {
  background-color: #4cd964;
}

.install-tag {
  background-color: #007aff;
}

.service-status {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  color: #ff3b30; /* 异常订单状态颜色改为红色 */
}

.price {
  font-size: 36rpx;
  font-weight: bold;
  margin-top: 5rpx;
}

/* 地址 */
.order-address {
  margin-bottom: 20rpx;
  padding-left: 60rpx;
}

.address-text {
  font-size: 28rpx;
  color: #666;
  line-height: 1.4;
}

/* 异常原因 */
.abnormal-reason {
  margin-bottom: 20rpx;
  padding: 15rpx;
  background-color: #fff5f5;
  border-radius: 8rpx;
  border-left: 4rpx solid #ff3b30;
}

.reason-label {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.reason-text {
  font-size: 28rpx;
  color: #ff3b30;
}

/* 查看详情按钮 */
.order-footer {
  display: flex;
  justify-content: flex-end;
}

.detail-btn {
  background-color: #fff;
  color: #0088ff;
  font-size: 28rpx;
  padding: 8rpx 30rpx;
  border-radius: 30rpx;
  border: 1px solid #0088ff;
  line-height: 1.5;
  margin: 0 10rpx 0 0;
}

.handle-btn {
  background-color: #ff3b30;
  color: #fff;
  font-size: 28rpx;
  padding: 8rpx 30rpx;
  border-radius: 30rpx;
  border: 1px solid #ff3b30;
  line-height: 1.5;
  margin: 0;
}

/* 无数据提示 */
.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  color: #999;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}
</style>